import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
from library_system import load_books_from_json, search_book, borrow_book, return_book, lost_book, Student, students, books

class LibraryApp:
    def __init__(self, root):
        """
        初始化图书管理系统GUI
        :param root: tkinter根窗口
        """
        self.root = root
        self.root.title("图书管理系统")
        self.root.geometry("1200x700")
        
        # 设置样式
        self.style = ttk.Style()
        self.style.theme_use('clam')
        
        # 加载数据
        self.load_data()
        
        # 创建主框架
        self.create_main_frame()
        
        # 创建搜索框和按钮
        self.create_search_frame()
        
        # 创建图书列表
        self.create_book_list()
        
        # 创建详情面板
        self.create_detail_panel()
        
        # 创建操作按钮
        self.create_action_buttons()
        
        # 当前选中的图书
        self.selected_book = None
        
        # 更新图书列表
        self.update_book_list()

    def load_data(self):
        """
        加载图书数据和学生信息
        """
        try:
            current_dir = os.path.dirname(os.path.abspath(__file__))
            json_file = os.path.join(current_dir, 'books.json')
            load_books_from_json(json_file)
            
            # 创建测试学生
            self.current_student = Student(1001)
            students.insert(self.current_student)
        except Exception as e:
            messagebox.showerror("错误", f"加载数据时出错：{str(e)}")

    def create_main_frame(self):
        """
        创建主窗口框架
        """
        self.main_frame = ttk.Frame(self.root, padding="10")
        self.main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

    def create_search_frame(self):
        """
        创建搜索框和搜索按钮
        """
        search_frame = ttk.Frame(self.main_frame)
        search_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
        
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=40)
        search_entry.grid(row=0, column=0, padx=5)
        
        search_button = ttk.Button(search_frame, text="搜索", command=self.search_books)
        search_button.grid(row=0, column=1, padx=5)

    def create_book_list(self):
        """
        创建图书列表（使用Treeview组件）
        """
        # 创建树形视图
        columns = ('title', 'authors', 'publisher', 'year', 'category', 'language')
        self.tree = ttk.Treeview(self.main_frame, columns=columns, show='headings')
        
        # 设置列标题
        self.tree.heading('title', text='书名')
        self.tree.heading('authors', text='作者')
        self.tree.heading('publisher', text='出版社')
        self.tree.heading('year', text='年份')
        self.tree.heading('category', text='类别')
        self.tree.heading('language', text='语言')
        
        # 设置列宽
        self.tree.column('title', width=200)
        self.tree.column('authors', width=150)
        self.tree.column('publisher', width=100)
        self.tree.column('year', width=70)
        self.tree.column('category', width=100)
        self.tree.column('language', width=70)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(self.main_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # 放置树形视图和滚动条
        self.tree.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=1, column=1, sticky=(tk.N, tk.S))
        
        # 绑定选择事件
        self.tree.bind('<<TreeviewSelect>>', self.on_select)

    def create_detail_panel(self):
        """
        创建图书详情面板
        """
        detail_frame = ttk.LabelFrame(self.main_frame, text="图书详情", padding="10")
        detail_frame.grid(row=1, column=2, sticky=(tk.W, tk.E, tk.N, tk.S), padx=10)
        
        # 创建详情标签
        self.detail_labels = {}
        fields = ['标题', '作者', '出版社', '年份', '类别', '子类别', '语言', '页数', '关键词', '摘要']
        for i, field in enumerate(fields):
            ttk.Label(detail_frame, text=f"{field}:").grid(row=i, column=0, sticky=tk.W, pady=2)
            self.detail_labels[field] = ttk.Label(detail_frame, text="", wraplength=300)
            self.detail_labels[field].grid(row=i, column=1, sticky=tk.W, pady=2)

    def create_action_buttons(self):
        """
        创建操作按钮（借阅、归还、报失、刷新）
        """
        button_frame = ttk.Frame(self.main_frame)
        button_frame.grid(row=2, column=0, columnspan=3, pady=10)
        
        ttk.Button(button_frame, text="借阅", command=self.borrow_selected_book).grid(row=0, column=0, padx=5)
        ttk.Button(button_frame, text="归还", command=self.return_selected_book).grid(row=0, column=1, padx=5)
        ttk.Button(button_frame, text="报失", command=self.report_lost_book).grid(row=0, column=2, padx=5)
        ttk.Button(button_frame, text="刷新", command=self.update_book_list).grid(row=0, column=3, padx=5)

    def update_book_list(self):
        """
        更新图书列表显示
        """
        # 清空现有项目
        for item in self.tree.get_children():
            self.tree.delete(item)
            
        # 添加所有图书
        if books.root:
            for book in books.inorder_traversal(books.root):
                self.tree.insert('', 'end', values=(
                    book.title,
                    ', '.join(book.authors),
                    book.publisher,
                    book.year,
                    book.category,
                    book.language
                ))

    def on_select(self, event):
        """
        处理图书选择事件
        :param event: 选择事件
        """
        selected_items = self.tree.selection()
        if not selected_items:
            return
            
        # 获取选中的图书
        item = selected_items[0]
        title = self.tree.item(item)['values'][0]
        self.selected_book = search_book(title)
        
        # 更新详情面板
        if self.selected_book:
            self.detail_labels['标题'].config(text=self.selected_book.title)
            self.detail_labels['作者'].config(text=', '.join(self.selected_book.authors))
            self.detail_labels['出版社'].config(text=self.selected_book.publisher)
            self.detail_labels['年份'].config(text=str(self.selected_book.year))
            self.detail_labels['类别'].config(text=self.selected_book.category)
            self.detail_labels['子类别'].config(text=self.selected_book.sub_category)
            self.detail_labels['语言'].config(text=self.selected_book.language)
            self.detail_labels['页数'].config(text=str(self.selected_book.page_count))
            self.detail_labels['关键词'].config(text=', '.join(self.selected_book.keywords))
            self.detail_labels['摘要'].config(text=self.selected_book.summary)

    def search_books(self):
        """
        搜索图书功能
        """
        search_text = self.search_var.get().strip()
        if not search_text:
            self.update_book_list()
            return
            
        # 清空现有项目
        for item in self.tree.get_children():
            self.tree.delete(item)
            
        # 搜索并显示结果
        book = search_book(search_text)
        if book:
            self.tree.insert('', 'end', values=(
                book.title,
                ', '.join(book.authors),
                book.publisher,
                book.year,
                book.category,
                book.language
            ))

    def borrow_selected_book(self):
        """
        借阅选中的图书
        """
        if not self.selected_book:
            messagebox.showwarning("提示", "请先选择一本书")
            return
            
        if borrow_book(self.current_student.id, self.selected_book.title):
            messagebox.showinfo("成功", f"成功借阅《{self.selected_book.title}》")
        else:
            messagebox.showerror("错误", "借阅失败")

    def return_selected_book(self):
        """
        归还选中的图书
        """
        if not self.selected_book:
            messagebox.showwarning("提示", "请先选择一本书")
            return
            
        if return_book(self.current_student.id, self.selected_book.title):
            messagebox.showinfo("成功", f"成功归还《{self.selected_book.title}》")
        else:
            messagebox.showerror("错误", "归还失败")

    def report_lost_book(self):
        """
        报失选中的图书
        """
        if not self.selected_book:
            messagebox.showwarning("提示", "请先选择一本书")
            return
            
        if lost_book(self.current_student.id, self.selected_book.title):
            messagebox.showinfo("成功", f"已报失《{self.selected_book.title}》")
            messagebox.showwarning("提示", f"您的信用分已扣除，当前信用分：{self.current_student.credit}")
        else:
            messagebox.showerror("错误", "报失失败")

def main():
    """
    程序入口函数
    """
    root = tk.Tk()
    app = LibraryApp(root)
    root.mainloop()

if __name__ == "__main__":
    main() 